/**
 * @author hhlxy
 * @version 1.0
 * @since 2025/8/5
 * 评论控制器类，负责处理与评论相关的HTTP请求
 */
package cn.yilongquan.controller;

import cn.yilongquan.authorize.PreAuthorize;
import cn.yilongquan.user.domain.Comment;
import cn.yilongquan.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 评论控制器，提供评论的增删改查及点赞相关接口
 */
@Api(value = "comment相关的接口", tags = "评论管理")
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 给评论点赞
     * @param commentId 评论ID
     * @return 点赞后的点赞数
     */
    @ApiOperation(value = "给指定评论点赞")
    @PostMapping("/star/{commentId}")
    @PreAuthorize(sn = "comment:star", name = "评论点赞", descs = "对指定评论进行点赞操作")
    public R starComment(@PathVariable String commentId) {
        Query query = new Query(Criteria.where("_id").is(commentId));
        Comment comment = mongoTemplate.findOne(query, Comment.class);
        if (comment == null) {
            return R.fail("评论不存在");
        }

        // 原子更新点赞数
        Update update = new Update().inc("likenum", 1);
        mongoTemplate.updateFirst(query, update, Comment.class);

        // 重新查询最新数据返回
        Comment updatedComment = mongoTemplate.findOne(query, Comment.class);
        return R.ok("likenum", updatedComment.getLikenum());
    }

    /**
     * 取消评论点赞
     * @param commentId 评论ID
     * @return 取消点赞后的点赞数
     */
    @ApiOperation(value = "取消对指定评论的点赞")
    @PostMapping("/unstar/{commentId}")
    @PreAuthorize(sn = "comment:unstar", name = "取消评论点赞", descs = "取消对指定评论的点赞操作")
    public R unstarComment(@PathVariable String commentId) {
        Query query = new Query(Criteria.where("_id").is(commentId));
        Comment comment = mongoTemplate.findOne(query, Comment.class);
        if (comment == null) {
            return R.fail("评论不存在");
        }

        int newLikeNum = Math.max(0, comment.getLikenum() - 1);
        Update update = new Update().set("likenum", newLikeNum);
        mongoTemplate.updateFirst(query, update, Comment.class);

        // 重新查询最新数据返回
        Comment updatedComment = mongoTemplate.findOne(query, Comment.class);
        return R.ok("likenum", updatedComment.getLikenum());
    }

    /**
     * 根据文章ID查询所有评论
     * @param articleId 文章ID
     * @return 评论列表
     */
    @ApiOperation(value = "根据文章ID查询评论列表")
    @GetMapping("/all/{articleId}")
    @PreAuthorize(sn = "comment:findByArticleId", name = "按文章查询评论", descs = "根据文章ID查询该文章下的所有评论")
    public R findAll(@PathVariable("articleId") Long articleId) {
        Query query = new Query(Criteria.where("articleId").is(articleId));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        // 新增日志：打印查询结果
        System.out.println("查询 articleId: " + articleId);
        System.out.println("查询到评论数量: " + comments.size());
        System.out.println("评论内容: " + comments);
        return R.ok(comments);
    }

    /**
     * 添加新评论
     * @param comment 评论对象，包含文章ID、评论内容等信息
     * @return 操作结果
     */
    @ApiOperation(value = "添加新评论")
    @PostMapping
    @PreAuthorize(sn = "comment:add", name = "添加评论", descs = "向指定文章添加新评论")
    public R addComment(@RequestBody Comment comment) {
        // 1. 校验必要字段（如 articleId、content、userId 等）
        if (comment.getArticleId() == null || comment.getContent() == null) {
            return R.fail("文章ID和评论内容不能为空");
        }

        // 2. 补充默认字段（如创建时间、点赞数默认 0）
        comment.setCreateTime(new Date());
        comment.setLikenum(0);
        comment.setUserId(1L); // 假设 userId 固定为 1，实际需从登录态获取

        // 3. 保存到 MongoDB
        mongoTemplate.save(comment);

        return R.ok("评论提交成功");
    }
}
